var express = require('express');
var router = express.Router();
const jwt = require("jsonwebtoken");
const {secretKey} = require('../token');
const multiparty = require("multiparty");
const path = require('path');
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.get('/getSession',function(req,res){
  let user = req.session.user;
  res.send(user || {});
});

router.get('/removeSession',function(req,res){
  req.session.user = null;
  res.send("success");
});

router.get('/getToken',function(req,res){
  // 获取到客户端发送过来的 token
  const token = req.get('Authorization');
  // 将编码后的 token 再转换回来
  const user = jwt.verify(token.split(" ")[1], secretKey);
  res.send(user);
})

router.post("/upload", function (req, res) {
  var form = new multiparty.Form({ uploadDir: "./public/images" });
  form.parse(req, function (err, fields, files) {
    if (err) {
      res.send(err);
    } else {
      console.log(files.file);
      var p = files.file[0].path.substring(
        files.file[0].path.indexOf("images")
      );
      res.send({filename:path.basename(p)});
    }
  });
});

module.exports = router;
